//
//  LoginViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/8/21.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "LoginViewController.h"
#import "RentVieitor.h"
#import "LCMD5Tool.h"
#import "RegisterViewController.h"
#import "UserRegistViewController.h"




@interface LoginViewController ()<UITextFieldDelegate>

@end

@implementation LoginViewController {
    
    UITextField *phoneText;
    UITextField *numText;
    MBProgressHUD *HUD;
    UIButton *getButton;
    UIButton *loginBtn;
    NSInteger getcodeTime;

}

- (void)viewWillAppear:(BOOL)animated {
    
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.title = @"登录";
    self.view.backgroundColor = [UIColor whiteColor];
    [self creatLeftView];
    [self creatView];
}

- (void)creatLeftView {
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 64)];
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(15, 20+12, 100,30);
    [leftBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 10, 70)];
    [leftBtn setImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
//    self.navigationItem.leftBarButtonItem = leftItem;
    [view addSubview:leftBtn];
    [self.view addSubview:view];
    // 自定义导航栏左侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(KWidth-65, 20+10, 50, 20);
    [rightBtn setTitle:@"注册" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor colorWithRed:99/255.0 green:99/255.0 blue:99/255.0 alpha:1] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
//    self.navigationItem.rightBarButtonItem = rightItem;
    [view addSubview:rightBtn];
    
    
}

//创建UI
- (void)creatView {
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20+64,KWidth-40 , 20)];
    titleLabel.text = @"手机快捷登录";
    titleLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:titleLabel];
    
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 50+64,KWidth-40 ,50)];
    contentLabel.text = @"未注册过的手机号将自动创建租客网用户账号,经纪人不会看到你的手机号";
    contentLabel.textColor = [UIColor colorWithRed:99/255.0 green:99/255.0 blue:99/255.0 alpha:1];
    contentLabel.font = [UIFont systemFontOfSize:14];
    contentLabel.numberOfLines = 0;
    [self changeLineSpaceForLabel:contentLabel WithSpace:5.0];
    [self.view addSubview:contentLabel];
    
    
    phoneText = [[UITextField alloc] initWithFrame:CGRectMake(20, 130+64, KWidth-40-100, 40)];
    phoneText.placeholder = @"请输入手机号码";
    phoneText.delegate = self;
    phoneText.keyboardType = UIKeyboardTypeNumberPad;
    phoneText.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:phoneText];
    
    getButton = [UIButton buttonWithType:UIButtonTypeSystem];
    getButton.frame = CGRectMake(KWidth-100, 130+64, 80, 40);
    [getButton setTitleColor:[UIColor colorWithRed:99/255.0 green:99/255.0 blue:99/255.0 alpha:1] forState:UIControlStateNormal];
    [getButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [getButton addTarget:self action:@selector(getNumber) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:getButton];
    
    CALayer *lineLayer = [CALayer layer];
    lineLayer.backgroundColor = [[UIColor colorWithRed:217/255.0 green:217/255.0 blue:217/255.0 alpha:1] CGColor];
    lineLayer.frame = CGRectMake(20,170+64, KWidth-40, 1);
    [self.view.layer addSublayer:lineLayer];
    
    numText = [[UITextField alloc] initWithFrame:CGRectMake(20, 190+64, KWidth-40-100, 40)];
    numText.placeholder = @"请输入验证码";
    numText.delegate = self;
    numText.keyboardType = UIKeyboardTypeNumberPad;
    numText.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:numText];
    
    CALayer *lineLayer2 = [CALayer layer];
    lineLayer2.backgroundColor = [[UIColor colorWithRed:217/255.0 green:217/255.0 blue:217/255.0 alpha:1] CGColor];
    lineLayer2.frame = CGRectMake(20,230+64, KWidth-40, 1);
    [self.view.layer addSublayer:lineLayer2];
    
    loginBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    loginBtn.frame = CGRectMake(20, 250+64, KWidth-40, 40);
    [loginBtn setBackgroundColor:[UIColor colorWithRed:249/255.0 green:105/255.0 blue:39/255.0 alpha:1]];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.layer.masksToBounds = YES;
    [loginBtn addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    loginBtn.layer.cornerRadius = 2;
    [self.view addSubview:loginBtn];
    
    UIButton *userButton = [UIButton buttonWithType:UIButtonTypeSystem];
    userButton.frame = CGRectMake(50 , 300+64, KWidth-100 , 20);
    [userButton setTitleColor:[UIColor colorWithRed:99/255.0 green:99/255.0 blue:99/255.0 alpha:1] forState:UIControlStateNormal];
    userButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [userButton setBackgroundColor:[UIColor clearColor]];
    [userButton setTitle:@"账号密码登录" forState:UIControlStateNormal];
    [userButton addTarget:self action:@selector(userNameAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:userButton];
}

//获取验证码
- (void)getNumber {
    
    getButton.enabled = NO;
    NSString *request = [self valiMobile:phoneText.text];
    
    //判断电话号码
    if (request != nil) {
        
        getButton.enabled = YES;
        [APPDELEGATE showPro:@"手机格式不正确"];
        return;
    }
    
    getcodeTime = 60;
    [getButton setTitle:[NSString stringWithFormat:@"%ld",(long)getcodeTime] forState:UIControlStateDisabled];
    
    
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(getCodeBtnTimerOut:) userInfo:nil repeats:YES];
    
    NSString *urlstr= @"http://api2.zuke.com/login/sendsms";
    NSString *md5String = [NSString stringWithFormat:@"%@Zuke.Com.App%@",phoneText.text,urlstr];
    //32位小写
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    md5String = [md5String stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSDictionary *param = @{@"mobile":phoneText.text,
                            @"sign":md5String
                            };
    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    manger.responseSerializer=[AFHTTPResponseSerializer serializer];
    manger.requestSerializer.timeoutInterval= 60;
    [manger POST:urlstr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSDictionary* jsonDic = [NSJSONSerialization
                                 JSONObjectWithData:responseObject
                                 options:kNilOptions
                                 error:nil];
        
        if ([jsonDic[@"code"] isEqualToString:@"10000"]) {
            
            [APPDELEGATE showPro:@"验证码已发送"];
            
        }else {
            getButton.enabled = YES;
            [APPDELEGATE showPro:jsonDic[@"message"]];
            getButton.enabled = YES;
            [getButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        getButton.enabled = YES;
        [APPDELEGATE showPro:@"网络错误"];
    }];
    

    
}

#pragma mark - 时间倒计时
- (void) getCodeBtnTimerOut:(NSTimer *)timer{
    
    getcodeTime--;
    if (getcodeTime > 0) {
        [getButton setTitle:[NSString stringWithFormat:@"%ld",(long)getcodeTime] forState:UIControlStateDisabled];
    }else{
        
        getButton.enabled = YES;
        [getButton setTitle:@"重获验证码" forState:UIControlStateNormal];
        [timer invalidate];
    }
    
}

//登录
- (void)loginAction {
    
    loginBtn.enabled = NO;
    NSString *request = [self valiMobile:phoneText.text];
    if (request != nil) {
        
        [APPDELEGATE showPro:@"手机格式不正确"];
        loginBtn.enabled = YES;
        return;
    }
    
    if (numText.text.length==0) {
        
        [APPDELEGATE showPro:@"请输入验证码"];
        loginBtn.enabled = YES;
        return;
    }
    

    NSString *urlstr= @"http://api2.zuke.com/login/sms";
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@%@",phoneText.text,numText.text,APPKEY_URL,urlstr];
    //32位小写
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSDictionary *param = @{
                            
                            @"mobile":phoneText.text,
                            @"smscode":numText.text,
                            @"sign":md5String
                            
                            };
    
    __weak typeof(self)weakSelf = self;
    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    manger.responseSerializer=[AFHTTPResponseSerializer serializer];
    manger.requestSerializer.timeoutInterval= 60;
    [manger POST:urlstr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        loginBtn.enabled = YES;
        NSDictionary* jsonDic = [NSJSONSerialization
                                 JSONObjectWithData:responseObject
                                 options:kNilOptions
                                 error:nil];
        
        if ([jsonDic[@"code"] isEqualToString:@"10000"]) {
            //登录成功
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            NSDictionary *dataDic = jsonDic[@"data"];
            dataDic = [Utils nullDic:dataDic];
            [defaults setObject:dataDic forKey:User_listsKey];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:nil userInfo:nil];
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }else {
            
            getButton.enabled = YES;
            [APPDELEGATE showPro:jsonDic[@"message"]];
            
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        getButton.enabled = YES;
        loginBtn.enabled = YES;
        [APPDELEGATE showPro:@"网络错误"];
    }];

}

//注册
- (void)registerAction {
    
    RegisterViewController *regVc = [[RegisterViewController alloc] init];
    [self presentViewController:regVc animated:YES completion:nil];
}

//返回
- (void)backAction {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//账号密码登录
- (void)userNameAction {
    
    UserRegistViewController *registVc = [[UserRegistViewController alloc] init];
    [self presentViewController:registVc animated:YES completion:nil];
}


//验证手机号
- (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return @"手机号长度只能是11位";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        }else{
            return @"请输入正确的电话号码";
        }
    }
    return nil;
}


//改变行间距
- (void)changeLineSpaceForLabel:(UILabel *)label WithSpace:(float)space {
    
    NSString *labelText = label.text;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:space];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    label.attributedText = attributedString;
    [label sizeToFit];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

@end
